package com.lf.mygpt.web;

import com.lf.mygpt.domain.Question;
import com.lf.mygpt.service.DashVectorService;
import com.lf.mygpt.service.GPTService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

@RestController
@RequestMapping("/api/question")
public class QuestionResource {

    private final DashVectorService dashVectorService;
    private final GPTService gptService;

    public QuestionResource(DashVectorService dashVectorService, GPTService gptService) {
        this.dashVectorService = dashVectorService;
        this.gptService = gptService;
    }

    /**
     * 初始化问题向量
     * @param questionList questionList 问题列表
     */
    @PostMapping("/init-vector")
    public void initQuestionToDashVector(@RequestBody List<Question> questionList) {
        dashVectorService.initQuestionToDashVector(questionList);
    }

    /**
     * 根据问题进行向量查询
     * @param question 用户的问题文本
     * @return 相关的初始问题知识列表
     */
    @PostMapping("/search")
    public List<Question> search(@RequestBody Question question) {
        return dashVectorService.searchQuestion(question.getQuestion());
    }

    /**
     * GPT正常聊天
     * @param question 用户的问题
     * @return SseEmitter
     */
    @PostMapping("/chat")
    public SseEmitter chat(@RequestBody Question question) {
        return gptService.chatCompletions(question.getQuestion());
    }

    /**
     * 依据我们私有的知识与 GPT 进行聊天
     * @param question 用户的问题
     * @return SseEmitter
     */
    @PostMapping("/chat-with-question")
    public SseEmitter chatWithQuestion(@RequestBody Question question) {
        // 先根据向量查询语义相近的语料
        List<Question> questionList = dashVectorService.searchQuestion(question.getQuestion());
        // 构造 GPT 的输入，拼接相关的资料和用户的问题
        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("你是一个光伏新能源领域的专家，请根据提供资料为用户解答问题\n");
        promptBuilder.append("提供的资料: \n");
        for (Question similarQuestion : questionList) {
            promptBuilder.append(similarQuestion.getQuestion()).append("\n");
            promptBuilder.append(similarQuestion.getAnswer()).append("\n");
        }
        promptBuilder.append("用户提问: \n");
        promptBuilder.append(question.getQuestion());
        return gptService.chatCompletions(promptBuilder.toString());
    }



}
